<div id="user_plati_platiefectuate"></div>
<script type="text/javascript">
		
Ext.onReady(function(){	
		var ds_plati;
		var sm_plati;
		var cm_plati;
		var fp_w_user_plati_introducere;
		var w_user_plati_platiefectuate;
		var fp_w_user_plati_modificare_platiefectuate
		var w_user_plati_modificare_platiefectuate;
		var htmlEditor1;
		var htmlEditor2;
		var htmlEditor11;
		var htmlEditor12; 

		htmlEditor1 = new Ext.form.HtmlEditor({
			allowBlank		:false,
			blankText		:'Reguli validare <br /><i>Camp obligatoriu</i>', 												
            fieldLabel		:'Explicatie',
            name			:'explicatie',
			height			:120,
            anchor			:'90%',
	        enableColors	:false,
	        enableAlignments:false,
			enableFont		:false,
			enableFontSize	:false,
			enableLinks		:false,
			enableSourceEdit:false,
			fontFamilies	:['Tahoma'],
			autoMonitorDesignMode:false																	
		});	
		htmlEditor2 = new Ext.form.HtmlEditor({
			allowBlank		:false,
			blankText		:'Reguli validare <br /><i>Camp obligatoriu</i>', 												
            fieldLabel		:'Obs.',
            name			:'observatii',
			height			:120,
            anchor			:'90%',
	        enableColors	:false,
	        enableAlignments:false,
			enableFont		:false,
			enableFontSize	:false,
			enableLinks		:false,
			enableSourceEdit:false,
			fontFamilies	:['Tahoma'],
			autoMonitorDesignMode:false																	
		});	
		htmlEditor11 = new Ext.form.HtmlEditor({
			allowBlank		:false,
			blankText		:'Reguli validare <br /><i>Camp obligatoriu</i>', 												
            fieldLabel		:'Explicatie',
            name			:'explicatie',
			height			:120,
            anchor			:'90%',
	        enableColors	:false,
	        enableAlignments:false,
			enableFont		:false,
			enableFontSize	:false,
			enableLinks		:false,
			enableSourceEdit:false,
			fontFamilies	:['Tahoma'],
			autoMonitorDesignMode:false,
			validateValue	: function(){
				 if (this.getValue() !== ''){
	                 this.clearInvalid();
	                 return true; 																						 	
				 } else {
	                 this.markInvalid(this.blankText);
	                 return false;																						 	
				 }
			}																				
		});	
		htmlEditor12 = new Ext.form.HtmlEditor({
			allowBlank		:false,
			blankText		:'Reguli validare <br /><i>Camp obligatoriu</i>', 												
            fieldLabel		:'Obs.',
            name			:'observatii',
			height			:120,
            anchor			:'90%',
	        enableColors	:false,
	        enableAlignments:false,
			enableFont		:false,
			enableFontSize	:false,
			enableLinks		:false,
			enableSourceEdit:false,
			fontFamilies	:['Tahoma'],
			autoMonitorDesignMode:false,
			validateValue	: function(){
				 if (this.getValue() !== ''){
	                 this.clearInvalid();
	                 return true; 																						 	
				 } else {
	                 this.markInvalid(this.blankText);
	                 return false;																						 	
				 }
			}																				
		});		
		
		function getExcel() {
		        if (!Ext.fly('tbExcel')) {
		            return {
		                xtype: 'tbbutton',
		                id: 'tbExcel',
						text:'Excel',
						tooltip:'Exporta in excel',
						iconCls:'b_excel_cls',
		                handler: function() {
		                    //create dummy form
		                    if (!Ext.fly('frmDummy')) {
		                        var frm = document.createElement('form');
		                        frm.id = 'frmDummy';
		                        frm.name = id;
		                        frm.className = 'x-hidden';
		                        document.body.appendChild(frm);
		                    }
		                    //get attachment
								Ext.Ajax.request({
								   url: 'user/functionalitati/excel/' + Math.random(),
								   disableCaching	:false,
								   isUpload			:true,
								   params:{
										saferequest	:true,
										table		:'plati_efectuate',
										filename	: 'raport',
										cyDep		:true,	
										active		:false,
										start 		:grid_user_plati_platiefectuate.store.lastOptions.params.start,
										limit		:grid_user_plati_platiefectuate.store.lastOptions.params.limit,
										sort		:grid_user_plati_platiefectuate.store.lastOptions.params.sort,
										dir			:grid_user_plati_platiefectuate.store.lastOptions.params.dir,
										fields		:grid_user_plati_platiefectuate.store.lastOptions.params.fields,
										query		:grid_user_plati_platiefectuate.store.lastOptions.params.query																			   	
								   },
		                        form: Ext.fly('frmDummy')
		                    });
		                }
		            };
		
		        } else {
		            return Ext.getCmp('tbExcel');
		        }
		} 	
						
		function plati_add(){
			if (!w_user_plati_platiefectuate) {
						// adaugare plata form panel	-----------------------------------------------------
						//-----------------------------------------------------------------------------------
							
						fp_w_user_plati_introducere = new Ext.FormPanel({
									id: "frm-plati-add-" + Math.random(),
									monitorValid:true,
									labelAlign: 'top',
									bodyStyle: 'padding:5px',
							        layout:'column',
							        border:false,								
									items: [{
							            columnWidth:0.5,
										defaultType: 'textfield',
							            layout: 'form',
										border:false,
										items:[new Ext.form.ComboBox({
													anchor		:'90%',	
													fieldLabel	:'Modalitate de plata',
													name		:'n-tip-plata', 
													allowBlank	:false, 
													blankText	:'Reguli validare <br /><i>Camp obligatoriu</i>',
													editable	:false,								
													lazyRender	:true,
													store		:new Ext.data.Store({
																     id			:'tip_plata_ds',
																	 baseParams	:{saferequest:true,code:'pay_mode'},
																     proxy		:new Ext.data.HttpProxy({
																     				url		:'common/getReference/' + Math.random()
																 	}),
																	 reader		: new Ext.data.JsonReader({
																							        root	:'DS_PAY_MODE',
																							        id		:'value',
																							        fields	:['value', 'option']
																	})
													}),
													hiddenName		:'modalitate',
													displayField	:'option',
													valueField		:'value',									
													triggerAction	:'all',
													emptyText		:'[Selectati tipul]'
											}),new Ext.form.DateField({
													anchor		:'90%',
						                        	fieldLabel	:'Data',
						                        	name		:'data',
													allowBlank	:false,
													blankText	:'Reguli validare <br /><i>Camp obligatoriu</i>',	
													readOnly 	:true,
													invalidText :'{value} nu este o data valida - Formatul corect este: aaaa-ll-zz',
													blankText	:'Reguli validare <br /><i>Camp obligatoriu</i><br /><i>Format: aaaa-ll-zz</i>',
													format		:'Y-m-d'
	                    						}),{
												       	allowBlank	:false,
														blankText	:'Reguli validare <br /><i>Camp obligatoriu</i>',
														fieldLabel	:'Numar',
														id			:'id-numar',
														name		:'numar',
														anchor		:'90%'																	   
												},new Ext.form.NumberField({
												       	allowBlank	:false,
														blankText	:'Reguli validare <br /><i>Camp obligatoriu</i>',
														fieldLabel	:'Valoare',
														id			:'id-valoare',
														name		:'valoare',
														anchor		:'90%'																	   
												}),{
														allowBlank	:false,
														blankText	:'Reguli validare <br /><i>Camp obligatoriu</i>',														
														fieldLabel	:'Beneficiar',
														id			:'id-beneficiar',														
														name		:'beneficiar',
														anchor		:'90%'
												}
										]										
									},{
							            columnWidth:0.5,
										defaultType: 'textfield',
							            layout: 'form',
										border:false,
										items:[htmlEditor1,htmlEditor2]										
									}],
							        buttons: [{
											text	:'Save and Close',
						            		tooltip	:'Salvati si Inchideti',
											formBind:true,
											handler : function(){
												if (fp_w_user_plati_introducere.getForm().isValid()) {
													fp_w_user_plati_introducere.getForm().submit({
														url: "common/insertTable/" + Math.random(),
														params: {
															saferequest: true,
															table: 'plati',
															cyDep: true
														},
														waitTitle: 'Connecting',
														waitMsg: 'Validating and saving data...',
														success: function(form, action, o){
															if (action.result.code == 0) {
																Ext.MessageBox.alert('Atentie:', 'Eroare la adaugare');
																fp_w_user_plati_introducere.getForm().reset();
															}
															else 
																if (action.result.code == 1) {
																	Ext.MessageBox.alert('Mesaj:', 'Adaugare efectuata cu succes!');
																	ds_plati.reload();
																	fp_w_user_plati_introducere.getForm().reset();
																	w_user_plati_platiefectuate.hide();
																}
														},
														failure: function(form, action, o){
															if (action.failureType == 'server') {
																Ext.Msg.alert('Warning', 'Cannot save to database!', obj.errors.reason);
															}
															else {
																Ext.Msg.alert('Warning!', 'Authentication server is unreachable!');
															}
															fp_w_user_plati_introducere.getForm().reset();
														}
													})
												}												
											}
										},{
											text: 'Reset',
											tooltip:'Resetati',
											handler: function(){
												fp_w_user_plati_introducere.getForm().reset();
											}	
										}
									]													
						});									
						// end adaugare plata form panel	-------------------------------------------------
						//-----------------------------------------------------------------------------------	
															
							w_user_plati_platiefectuate = new Ext.Window({
								id				:'w-user-plati-platiefectuate' + Math.random(),
								title			:'Adaugare plata',
								animateTarget	:'b-add',
								width			:610,
								height			:400,
								plain			:true,
								modal			:true,
								closeAction		:'hide',
								items			:fp_w_user_plati_introducere,
								loadMask		:{msg:'Loading...'},
					            buttons: [{
								    text		:'Cancel',
									tooltip		:'Renuntati',
								    handler		:function(){
										fp_w_user_plati_introducere.getForm().reset();
								        w_user_plati_platiefectuate.hide();
								    }
								}]
						
							});								

			}else {}
			w_user_plati_platiefectuate.show(null, htmlEditor1.checkDesignMode, htmlEditor1, htmlEditor2.checkDesignMode, htmlEditor2);	
		}	
		
		function plati_edit(sID){
			if (!w_user_plati_modificare_platiefectuate) {
						// editare plata form panel	-----------------------------------------------------
						//-----------------------------------------------------------------------------------	
						fp_w_user_plati_modificare_platiefectuate = new Ext.FormPanel({
								id			:"frm-plati-edit-" + Math.random(),
								monitorValid:true,
								labelAlign	:'top',
								bodyStyle	:'padding:5px',
						        layout		:'column',
						        border		:false,	
								items: [{
						            columnWidth:0.5,
									defaultType: 'textfield',
						            layout: 'form',
									border:false,
									items:[new Ext.form.Hidden({          
										  	fieldLabel: 'ID',  
										  	name: 'ID'
										}),new Ext.form.ComboBox({
												anchor		:'90%',	
												fieldLabel	:'Modalitate de plata',
												name		:'n_modalitate', 
												allowBlank	:false,
												blankText	:'Reguli validare <br /><i>Camp obligatoriu</i>', 
												editable	:false,							
												lazyRender	:true,
												store		:new Ext.data.Store({
															     id			:'tip_plata_ds',
																 autoLoad	:true,
																 baseParams	:{saferequest:true,code:'pay_mode'},
															     proxy		:new Ext.data.HttpProxy({
															     				url		:'common/getReference/' + Math.random()
															 	}),
																 reader		: new Ext.data.JsonReader({
																		        root	:'DS_PAY_MODE',
																		        id		:'value',
																		        fields	:['value', 'option']
																})
												}),
												hiddenName		:'modalitate',
												displayField	:'option',
												valueField		:'value',									
												triggerAction	:'all',
												emptyText		:'[Selectati Modalitate]'							
										}),new Ext.form.DateField({
												anchor		:'90%',
					                        	fieldLabel	:'Data',
					                        	name		:'data',
												allowBlank	:false,
												blankText	:'Reguli validare <br /><i>Camp obligatoriu</i>',	
												readOnly 	:true,
												invalidText :'{value} nu este o data valida - Formatul corect este: aaaa-ll-zz',
												blankText	:'Reguli validare <br /><i>Camp obligatoriu</i><br /><i>Format: aaaa-ll-zz</i>',
												format		:'Y-m-d'
                    						}),{
											       	allowBlank	:false,
													blankText	:'Reguli validare <br /><i>Camp obligatoriu</i>',
													fieldLabel	:'Numar',
													name		:'numar',
													anchor		:'90%'																	   
											},new Ext.form.NumberField({
											       	allowBlank	:false,
													blankText	:'Reguli validare <br /><i>Camp obligatoriu</i>',
													fieldLabel	:'Valoare',
													name		:'valoare',
													anchor		:'90%'																	   
											}),{
													allowBlank	:false,
													blankText	:'Reguli validare <br /><i>Camp obligatoriu</i>',														
													fieldLabel	:'Beneficiar',														
													name		:'beneficiar',
													anchor		:'90%'
											}
									]										
								},{
						            columnWidth:0.5,
									defaultType: 'textfield',
						            layout: 'form',
									border:false,
									items:[htmlEditor11,htmlEditor12]										
								}],
						        buttons: [{
											text	:'Save and Close',
						            		tooltip	:'Salvati si Inchideti',
											formBind:true,
											handler : function(){
												if (fp_w_user_plati_modificare_platiefectuate.getForm().isValid()) {
					           						fp_w_user_plati_modificare_platiefectuate.getForm().submit({
													  		url: "common/updateTable/" + Math.random(),
															params:{saferequest:true,table:'plati'},
													  		waitTitle: 'Connecting..',
													  		waitMsg: 'Validating and saving data...',										
															success:function(form, action, o) {
																if(action.result.code === 0){
																	Ext.MessageBox.alert('Atentie:', 'Eroare la actualizare');
																	fp_w_user_plati_modificare_platiefectuate.getForm().reset(); 	
																}else if(action.result.code == 1){
																		Ext.MessageBox.alert('Mesaj:', 'Actualizare efectuata cu succes!');
																		ds_plati.reload();
																		fp_w_user_plati_modificare_platiefectuate.getForm().reset();
																		w_user_plati_modificare_platiefectuate.hide();
																}
															},										
															failure: function(form, action, o){
									                            if(action.failureType == 'server'){
									                                Ext.Msg.alert('Warning', 'Cannot save to database!', obj.errors.reason);
									                            }else{
									                                Ext.Msg.alert('Warning!', 'Authentication server is unreachable!');
									                            }
																fp_w_user_plati_modificare_platiefectuate.getForm().reset();	
															}
												  	})
												}	
									  		}	
						        		},{
											text: 'Reset',
											tooltip:'Resetati',
											handler: function(){	
												fp_w_user_plati_modificare_platiefectuate.getForm().reset();
											}
										}
								]														
						});										
						
						// end adaugare plata form panel	-------------------------------------------------
						//-----------------------------------------------------------------------------------	
															
							w_user_plati_modificare_platiefectuate = new Ext.Window({
								id			:'w-user-modificare-plata' + Math.random(),
								title		:'Modificare plata',
								width		:610,
								height		:420,
								plain		:true,
								modal		:true,
								closeAction	:'hide',
								items		:fp_w_user_plati_modificare_platiefectuate,
								loadMask	:{msg:'Loading...'},
					            buttons: [{
								    text	:'Cancel',
									tooltip	:'Renuntati',
								    handler	:function(){
										fp_w_user_plati_modificare_platiefectuate.getForm().reset();
								        w_user_plati_modificare_platiefectuate.hide();
								    }
								}]
						
							});								

			}else {}
			w_user_plati_modificare_platiefectuate.show();	
			
			fp_w_user_plati_modificare_platiefectuate.getForm().load({
				url:'common/selectTableWhere/' + Math.random(),                          
				waitMsg:'Loading',
				params:{saferequest:true,table:"plati",ID:sID}
			});	
		}		
		function doDelete(btn){
			if (btn == 'yes') {
				var selections = grid_user_plati_platiefectuate.selModel.getSelections();
				var prez = [];
				for (i = 0; i < grid_user_plati_platiefectuate.selModel.getCount(); i++) {
					prez.push(selections[i].json.ID);
				}
				var encoded_array = Ext.encode(prez);
				Ext.Ajax.request({
					waitMsg: 'Va rugam asteptati',
					url: 'common/deleteTable/' + Math.random(),
					params: {
						saferequest: true,
						table: 'plati',
						ids: encoded_array
					},
					success: function(response){
						var result = eval(response.responseText);
						switch (result) {
							case 1:
								ds_plati.reload();
								break;
							default:
								Ext.MessageBox.alert('Warning', 'Nu puteti sterge toate inregistrarile selectate');
								break;
						}
					},
					failure: function(response){
						var result = response.responseText;
						Ext.MessageBox.alert('error', 'could not connect to the database. retry later');
					}
				});
				
			}
		}	
	
		function plati_delete(){
			if (grid_user_plati_platiefectuate.selModel.getCount() == 1) {
				Ext.MessageBox.confirm('Confirmation', 'Sunteti pe cale de a sterge o inregistrare. Continuati?', doDelete);
			}
			else 
				if (grid_user_plati_platiefectuate.selModel.getCount() > 1) {
					Ext.MessageBox.confirm('Confirmation', 'Stergeti inregistrarile selectate?', doDelete);
				}
				else {
					Ext.MessageBox.alert('Warning', 'Pentru a sterge inregistrari, selectati cel putin o inregistrare!');
				}
		}				
								
/**
 * grid
 * ************************************************************************
 */	
	    ds_plati = new Ext.data.Store({
			id			:'table_ds_plati_efectuate',
	        remoteSort	:true,
			baseParams	:{saferequest:true,table:'plati',cyDep:true},			
	        proxy: new Ext.data.HttpProxy({
	            url: 'common/getTable/' + Math.random()		
	        }),
	        reader: new Ext.data.JsonReader({
	            root: 'DS_PLATI',
	            totalProperty: 'totalCount',
	            id: 'ID',
	            fields: [
	                'data', 'beneficiar', 'valoare', 'numar', 'modalitate', 'explicatie', 'observatii'
	            ]
	        })
	    });
		ds_plati.setDefaultSort('numar', 'desc');
	    ds_plati.load({params:{start:0, limit:22}});
		
		sm_plati = new Ext.grid.CheckboxSelectionModel();

	    function rdr_modalitate(val){
	        if(val == 49){
	            return '<span style="color:green;">Cash</span>';
	        }else if(val == 50){
	            return '<span style="color:red;">Ordin de plata</span>';
	        }
	        return val;
	    }	
				
	    cm_plati = new Ext.grid.ColumnModel([sm_plati,
				{header: "Data",			dataIndex: 'data'},
				{header: "Beneficiar",		dataIndex: 'beneficiar'},
				{header: "Valoare",			dataIndex: 'valoare'},
				{header: "Numar document",	dataIndex: 'numar'},
				{header: "Modalitate",		dataIndex: 'modalitate', 	renderer:rdr_modalitate},
				{header: "Explicatie",		dataIndex: 'explicatie'}
		]);
    	cm_plati.defaultSortable = true;
		
	    grid_user_plati_platiefectuate = new Ext.grid.GridPanel({
			id:'grid-user-plati-plati-efectuate' + Math.random(),
	        renderTo:'user_plati_platiefectuate',			
	        height:569,//586,
	        anchor:'100%',						
			frame:false,				
	        title:'<?=$title?>',
	        store: ds_plati,
	        cm: cm_plati,
			sm: sm_plati,
	        loadMask: true,
	        viewConfig: {
	            forceFit:true
	        },
	        bbar: new Ext.PagingToolbar({
				beforePageText:'Pagina&nbsp;',
				afterPageText:'din {0}',
				firstText:'Prima pagina',
				lastText:'Ultima pagina',
				nextText:'Pagina urmatoare',
				prevText:'Pagina precedenta',   
	            pageSize: 22,
	            store: ds_plati,
	            displayInfo: true,
	            displayMsg: 'Plati {0} - {1} din {2}',
	            emptyMsg: "No records",
				plugins: new Ext.ux.Andrie.pPageSize({
					  beforeText:'',		
				      afterText: '&nbsp;inreg/pagina',
				      comboCfg: {width: 50}
				      })
			}),plugins: new Ext.ux.grid.Search({
						searchText:'Criterii',
						searchTipText:'Introduceti textul dorit...',
						iconCls:'b_search_cls',
						minChars:2,
						autoFocus:true,
						text:'Cauta dupa camp',
						mode:'remote',
						position:'top'
			}),
	        tbar:[{
				id		:'b-add',
	            text	:'Add ',
	            tooltip	:'Adaugati',
	            iconCls	:'b_add_cls',
				handler	:plati_add
	        },'-',{
	            text:'Delete',
	            tooltip:'Stergeti',
	            iconCls:'b_delete_cls',
				handler:plati_delete
	        },'-',getExcel()]
		});	
		
/**
 * 
 * @param {Object} grid
 * @param {Object} rowIndex
 * @param {Object} e
 */		
		
	grid_user_plati_platiefectuate.on('rowdblclick', function(grid, rowIndex, e) {
		if (grid_user_plati_platiefectuate.selModel.getCount() == 1) {
			var selection = grid_user_plati_platiefectuate.selModel.getSelections();
			plati_edit(selection[0].id);
		} else {
		  	Ext.MessageBox.alert('Warning','Pentru a modifica, selectati doar o inregistrare!');
		}
			
	});										
});	
	
</script>
